//app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    this.getOpenid();
    
    // 获取用户信息
    var that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              wx.setStorageSync('USER_INFO', res.userInfo);
              that.globalData.userInfo = res.userInfo;
    this.getUserInfo();
            },
            fail:err=>{
              // 未授权，跳转到授权页面
           wx.reLaunch({
             url: '/pages/wxauthorization/wxauthorization',
           })
            }
          })
        } else {
          // 未授权，跳转到授权页面
          wx.reLaunch({
            url: '/pages/wxauthorization/wxauthorization',
          })
        }
      }
    })
  },
  onShow: function () {
    var that = this;
  },
  getOpenid: function () { //获取openid 和 session_key
    var that = this;
    wx.removeStorageSync('OPENID')
    wx.removeStorageSync('SESSION_KEY')
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.request({
            url: that.globalData.applet_park_api_url + '/api/wechatApplet/jscode2session',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              jsCode: res.code,
            },
            success: function (res1) {
              if (res1.data) {
                wx.setStorageSync("OPENID", res1.data.data.openid);

                wx.setStorageSync("SESSION_KEY", res1.data.data.session_key);
                that.globalData.openId = res1.data.data.openid; //绑定全局openid
              } else {
                wx.showToast({
                  title: '获取用户信息失败',
                  icon: 'fail'
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '获取用户信息失败',
                icon: 'fail'
              });
            }
          })
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'fail'
          });
        }
      }
    });
  },
  getUserInfo: function (cb) { //获取用户信息 id token userInfo roles
    var that = this;
    wx.removeStorageSync('OPENID')
    wx.removeStorageSync('nickName')
    wx.removeStorageSync('userRoles')
    wx.removeStorageSync('id')
    wx.removeStorageSync('TOKEN')
    // wx.removeStorageSync('TOKEN')
    // wx.removeStorageSync('USER_INFO')
    if (!that.globalData) { //没有用户信息
      typeof cb == "function" && cb(that.globalData.userInfo)
    } else {
      wx.login({ //调用登录接口
        success: function (res) {
          if (res.code) {
            wx.request({
              url: that.globalData.applet_park_api_url + '/api/wechatApplet/jscode2session',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                jsCode: res.code,
              },
              success: function (res1) {
                if (res1.data.code == 0) {
                  wx.setStorageSync("OPENID", res1.data.data.openid);
                  wx.setStorageSync("SESSION_KEY", res1.data.data.session_key);
                  that.globalData.openId = res1.data.data.openid;
                  var openId = res1.data.data.openid
                  var userInfo = wx.getStorageSync("USER_INFO");
                  if (userInfo != undefined && userInfo != null) {
                    for (var pro in userInfo) {
                      that.globalData.userInfo[pro] = userInfo[pro];
                    }
                    //根据openid获取手机号的接口
                    wx.request({
                      url: that.globalData.applet_park_api_url + '/api/sysUsers/validateWx',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        wxOpenId: res1.data.data.openid,
                      },
                      success: function (res2) {
                        if (res2.data.code != 0) { //没有手机号 需要去身份认证
                          wx.navigateTo({
                            url: '../loginidentityList/loginidentityList',
                          })
                        } else {
                          var userInfo = wx.getStorageSync("USER_INFO");
                          if (userInfo) {
                            userInfo.bindPhone = res2.data.data.mobile;
                            userInfo.nickName = res2.data.data.nickName;
                          } 
                          wx.setStorageSync("USER_INFO", userInfo);
                          wx.setStorageSync("nickName", res2.data.data.nickName);
                          wx.setStorageSync("id", res2.data.data.id);
                          that.globalData.bindPhone = res2.data.data.bindPhone;
                          that.globalData.nickName = res2.data.data.nickName;
                          that.globalData.id = res2.data.data.id;
                          wx.setStorageSync("userRoles", res2.data.data.userRoles); //角色为空
                          that.globalData.userRoles = res2.data.data.userRoles;
                          wx.setStorageSync("TOKEN", res2.data.data.token);
                          that.globalData.TOKEN = res2.data.data.token;
                          wx.showToast({
                            title: '登录成功',
                            icon: 'success',
                          })
                          var pages = getCurrentPages();
                          for (var i = 0; i < pages.length; i++) {
                            if ((pages[i].route == "pages/wxauthorization/wxauthorization") || (pages[i].route == "pages/loginidentityList/loginidentityList")) {
                              wx.navigateTo({
                                url: '/pages/index/index',
                              })
                            }
                          }
                        }
                      },
                      fail: function () {
                        wx.showModal({
                          title: '获取用户手机号失败',
                          showCancel: false,
                          confirmText: '确认',
                          icon: 'none',
                          success(res) {
                            wx.navigateTo({
                              url: '../register/register',
                            })
                          }
                        })
                      }
                    })
                  }

                } else {
                  wx.showToast({
                    title: 'x',
                    icon: 'fail'
                  });
                }
              },
              fail: function () {
                wx.showToast({
                  title: '获取用户信息失败',
                  icon: 'fail'
                });
              }
            })
          } else {
            wx.showToast({
              title: '获取用户信息失败',
              icon: 'fail'
            });
          }
        }
      });
    }
  },
  globalData: {
    // 浙大森林
    // appid: "wxd11d9f69e7d4d55b",
    // secret: '88cdd694e5804167c07f5b89b5a56d20',
    // 金城食堂
    appid: "wxcc80ff4f9e7ee858",
    secret: '0a9418bcda67302058bd387d3451cba5',
    userInfo: {},
    id: '',
    openId: '',
    TOKEN: '',
    nickName: '',
    userRoles: '',
    applet_park_api_url: "https://localhost:9999",
    // applet_park_api_url: "https://192.168.31.212:9999",
    applet_park_api_url_img: "https://njdhy.com.cn:7777",
    //applet_park_api_url_imgst: "http://zjurainforest.com:7777",
    applet_park_api_url_imgUrl: 'http://221.226.72.214:9527',
    // applet_park_api_url_imgUrl: 'https://zjurainforest.com:9527',
    //applet_park_api_url: "https://39.98.65.212:9999",
    // applet_park_api_url: "http://47.104.225.193:7777",
    // 浙大森林ip
    // applet_park_api_url: "https://zjurainforest.com:9999",
    // 金城ip
    applet_park_api_url: "https://jinchengit.cn:9999",
  }
})